<template>
    <!-- 班级管理添加 -->
    <div>
        <!-- 编辑弹出框 -->
        <el-dialog title="修改班级" :visible.sync="findVisible" width="20" :before-close="beforeClose">
            <el-form ref="query" :rules="queryrules" :model="query" label-width="80px">
                <el-form-item style="width: 400px" placeholder="例：20-10" label="班级名称" prop="name">
                    <el-input v-model="query.name"></el-input>
                </el-form-item>
                <el-form-item label="班级别名" prop="classname">
                    <el-select v-model="query.classname" placeholder="请选择" change="xxx()">
                        <div v-for="(item, index) in classnamelist" :key="index">
                            <el-option :key="item.value" :label="item.value" :value="item.value"></el-option>
                        </div>
                    </el-select>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <!-- <el-button @click="findVisible = false">取 消</el-button> -->
                <el-button type="primary" @click="findinfo('query')">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 左上角元素 -->
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item> <em class="el-icon-lx-calendar"></em>班级管理 </el-breadcrumb-item>
                <el-breadcrumb-item>修改班级信息</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="form-box">
                <div class="form-position">
                    <el-form :rules="rules" ref="form" :model="form" label-width="80px">
                        <el-form-item label="班级名称" prop="name">
                            <el-input
                                style="width: 400px"
                                placeholder="例：20-10"
                                v-model="form.name"
                                maxlength="5"
                                show-word-limit
                                clearable
                            >
                            </el-input>
                        </el-form-item>

                        <el-form-item label="开班时间" prop="begindate">
                            <el-col :span="11">
                                <el-date-picker
                                    type="date"
                                    placeholder="选择日期"
                                    v-model="form.begindate"
                                    value-format="yyyy-MM-dd"
                                    style="width: 100%"
                                    @change="datechange"
                                ></el-date-picker>
                            </el-col>
                        </el-form-item>

                        <el-form-item label="主学课程" prop="course">
                            <el-radio-group v-model="form.course">
                                <el-radio label="java"></el-radio>
                                <el-radio label="前端"></el-radio>
                                <el-radio label="python"></el-radio>
                                <el-radio label="全栈"></el-radio>
                            </el-radio-group>
                        </el-form-item>

                        <el-form-item label="班级别名" prop="classname">
                            <el-select v-model="form.classname" placeholder="请选择" change="xxx()">
                                <div v-for="(item, index) in classnamelist" :key="index">
                                    <el-option :key="item.value" :label="item.value" :value="item.value"></el-option>
                                </div>
                            </el-select>
                        </el-form-item>

                        <el-form-item label="班主任" prop="headmaster">
                            <el-select v-model="form.headmaster" placeholder="请选择">
                                <div v-for="(item, index) in headmasterlist" :key="index">
                                    <el-option :key="item.value" :label="item.value" :value="item.value"></el-option>
                                </div>
                            </el-select>
                        </el-form-item>

                        <el-form-item label="课程时长" prop="duration">
                            <el-select v-model="form.duration" placeholder="请选择" @change="datechange">
                                <div v-for="(item, index) in durationlist" :key="index">
                                    <el-option :key="item.value" :label="item.label" :value="item.value"></el-option>
                                </div>
                            </el-select>
                        </el-form-item>

                        <el-form-item label="班级状态" prop="status">
                            <el-radio-group v-model="form.status" size="small">
                                <el-radio-button label="-1">试听</el-radio-button>
                                <el-radio-button label="0">在读</el-radio-button>
                                <el-radio-button label="1">毕业</el-radio-button>
                            </el-radio-group>
                        </el-form-item>

                        <el-form-item label="毕业时间" prop="enddate">
                            <el-col :span="11">
                                <el-date-picker
                                    type="date"
                                    placeholder="选择日期"
                                    v-model="form.enddate"
                                    value-format="yyyy-MM-dd"
                                    style="width: 100%"
                                    :disabled="true"
                                ></el-date-picker>
                            </el-col>
                        </el-form-item>

                        <el-form-item>
                            <el-button type="primary" @click="onSubmit('form')">提交修改</el-button>
                            <el-button  @click="goBack('form')">取消修改</el-button>
                        </el-form-item>
                    </el-form>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import { allHeadmaster, findClassByTwo, updateClass } from '../../api/index';
export default {
    name: 'updateclass',
    props: ['test'],
    mounted: function () {
        // this.getAllHeadMaster()
    },
    // 路由多次传值方法2
    // watch() {
    //     '$route'(to, form) {
    //         console.log(to)
    //         console.log(form)
    //     }
    // },
    data() {
        var validateName = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入班级名'));
            } else if (value.length != 5) {
                callback(new Error('班级名长度要5位'));
            } else {
                callback();
            }
        };
        return {
            findVisible: false,
            headmasterlist: [],
            classlist: [],
            query: {
                name: '',
                classname: ''
            },
            queryrules: {
                name: [{ required: true, validator: validateName, trigger: 'blur' },
                    { pattern: /^\d{2}-\d{2}$/, message: '班级名不合法，例：20-10' }],
                classname: [{ required: true, message: '请选择班级别名', trigger: 'change' }]
            },
            aaa: '',
            form: {
                name: '', //班级名称
                course: '', //课程名z
                classname: '', //班级别名
                enddate: '', //毕业时间
                status: '', //状态（毕业，未毕业）
                begindate: '', //开班时间
                headmaster: '', //班主任
                duration: '' //课程时长
            },
            rules: {
                name: [{ required: true, validator: validateName, trigger: 'blur' },
                    { pattern: /^\d{2}-\d{2}$/, message: '班级名不合法，例：20-10' }],
                begindate: [{ required: true, message: '请选择开班日期', trigger: 'blur' }],
                course: [{ required: true, message: '请选择主修课程', trigger: 'blur' }],
                classname: [{ required: true, message: '请选择班级别名', trigger: 'change' }],
                headmaster: [{ required: true, message: '请选择班主任', trigger: 'change' }],
                duration: [{ required: true, message: '请选择课程时长', trigger: 'change' }],
                status: [{ required: true, message: '请选择班级状态', trigger: 'change' }],
                enddate: [{ required: true, message: '请选择毕业时间', trigger: 'change' }]
            },
            classnamelist: [
                {
                    value: '王者班'
                },
                {
                    value: '荣耀班'
                },
                {
                    value: '英雄班'
                },
                {
                    value: '联盟班'
                }
            ],
            durationlist: [
                {
                    label: '4个月',
                    value: '4'
                },
                {
                    label: '5个月',
                    value: '5'
                },
                {
                    label: '6个月',
                    value: '6'
                }
            ]
        };
    },
    beforeRouteEnter(to, from, next) {
        // to是要跳转的路由
        // from是之前的路由
        console.log(to, from, next);
        next((vm) => {
            if (to.params.headmasterlist == undefined) {
                vm.getAllHeadMaster();
                vm.findVisible = true;
            } else {
                vm.headmasterlist = to.params.headmasterlist;
                vm.form = to.params.classlist;
                // console.log(vm.form)
                // console.log(vm.headmasterlist)
                vm.form.duration += '个月';
                vm.findVisible = false;
            }
        });
    },
    methods: {
        getAllHeadMaster() {
            allHeadmaster().then((res) => {
                console.log(res);
                this.headmasterlist = [];
                for (let i = 0; i < res.length; i++) {
                    this.headmasterlist.push({
                        value: res[i]
                    });
                }
            });
        },
        updateclass(callback) {
            console.log(this.form.duration);
            this.form.duration = this.form.duration.slice(0, 1);
            console.log(this.form.duration);
            updateClass(this.form).then((res) => {
                if (res == '修改成功') {
                    this.$message.success('修改成功！');
                    callback(true)
                } else {
                    this.$message.error('修改失败！');
                    callback(fasle)
                }
            });
        },

        /**
         * 通过开班时间和课程时长
         * 计算毕业时间
         */
        datechange() {
            // console.log(this.form.begindate)
            // console.log(this.form.duration)

            if (this.form.begindate == '' || this.form.duration == '') {
                return;
            } else {
                var beg_date = new Date(this.form.begindate);

                beg_date.setTime(beg_date.getTime() + 3600 * 1000 * 24 * 31 * this.form.duration);

                this.form.enddate = beg_date.getFullYear() + '-' + (beg_date.getMonth() + 1) + '-' + beg_date.getDate();
                console.log(this.form.enddate);
            }
        },
        /**
         * 提交修改的表单
         */
        onSubmit(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.updateclass(state => {
                        this.$router.push('findclass');
                    })
                } else {
                    this.$message.error('数据不能为空！');
                    return false;
                }
            });
        },
        /**
         * dialog的搜索事件
         */
        findinfo(formName) {
            // 校验表单数据是否存在空
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.findclassbytwo();
                } else {
                    this.$message.error('数据不能为空！');
                    return false;
                }
            });
        },
        /**
         * 通过名称、别名查找对应班级信息
         */
        findclassbytwo() {
            findClassByTwo(this.query).then((res) => {
                console.log(res);
                if (res == '班级不存在') {
                    this.$message.error('该班级不存在！');
                } else {
                    this.form = res;
                    this.form.duration += '个月';
                    this.findVisible = false;
                }
            });
        },
        /**
         * 触发dialog关闭时调用
         */
        beforeClose() {
            // 把dialog的开关设置为false
            this.findVisible = false;
            // 跳转到查找班级页面
            this.$router.push('findclass');
            // 获取当前页面在tagslist数组的下标
            var index = this.test.indexOf('updateclass');
            // console.log("下标")
            // console.log(index)
            // console.log("列表数组")
            // console.log(this.test)

            // 向Home发送获取到的下标
            this.$emit('updateclass', index)
        },
        goBack(formName){
            this.$router.go(-1);
            this.$refs[formName].resetFields();
        }
    }
};
</script>

<style scoped>
.form-box {
    height: 450px;
}
.form-position {
    width: 500px;
    /* border: 1px solid black; */
    position: absolute;
    left: 50%;
    transform: translateX(-60%);
}
</style>